/*
 * This file is part of the libsigrok project.
 *
 * Copyright (C) 2010 Uwe Hermann <uwe@hermann-uwe.de>
 * Copyright (C) 2011 Olivier Fauchon <olivier@aixmarseille.com>
 * Copyright (C) 2012 Alexandru Gagniuc <mr.nuke.me@gmail.com>
 * Copyright (C) 2015 Bartosz Golaszewski <bgolaszewski@baylibre.com>
 * Copyright (C) 2019 Frank Stettner <frank-stettner@gmx.net>
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see <http://www.gnu.org/licenses/>.
 */
#define _GNU_SOURCE
#include <pthread.h>

#include <config.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <libsigrok/libsigrok.h>
#include "libsigrok-internal.h"
#include "protocol.h"

#define ANALOG_SAMPLES_PER_PERIOD 20



static void send_analog_packet(struct analog_gen *ag, struct sr_dev_inst *sdi)
{
	struct sr_datafeed_packet packet;
	unsigned int i, j;
	float *data;
	int16_t *xdma_data;
    int ret;

	if (!ag->ch || !ag->ch->enabled)
		return;

    ret = rte_ring_dequeue(ag->rx_ring, (void**)&xdma_data);
    if (ret != 0) {
        //printf("no pkt from xdma\n");
        return;
    }

    //printf("get pkt from xdma\n");

	packet.type = SR_DF_ANALOG;
	packet.payload = &ag->packet;


	ag->packet.meaning->channels = g_slist_append(NULL, ag->ch);
	ag->packet.meaning->mq = ag->mq;
	ag->packet.meaning->mqflags = ag->mq_flags;

	ag->packet.meaning->unit = SR_UNIT_SECOND;

	//ag->packet.num_samples = (XDMA_BUFSIZE / 2) / 16;
	ag->packet.num_samples = (XDMA_BUFSIZE / 2);
    data = ag->packet.data;

	//int once = 0;
    //for (i = 0, j = 0; j < ag->packet.num_samples; i += 16, j++) {
    for (i = 0, j = 0; j < ag->packet.num_samples; i++, j++) {
#if 0
		if ((!once) && (xdma_data[i] >= 0x1000)) {
			printf("index %u, addr 0x%lx, data:%u, %d\n", devc->index, devc->addr, xdma_data[i], i);
			once = 1;
		}
#endif
        data[j] = xdma_data[i] / 100.0;
    }
	sr_session_send(sdi, &packet);
    rte_ring_enqueue(ag->free_ring, xdma_data);

    uint64_t curTime = g_get_monotonic_time();
    if (ag->lastSendTime) {
        ag->lastSendSamples += ag->packet.num_samples;
        uint64_t passTime = curTime - ag->lastSendTime;
        if (passTime > 1000000) {
            ag->lastSpeed = ag->lastSendSamples / passTime * 1000000;
            printf("channel %s sample speed %lu pps\n", ag->ch->name, ag->lastSpeed);

            ag->lastSendTime = curTime;
            ag->lastSendSamples = 0;
        }
    } else {
        ag->lastSendTime = curTime;
    }
}

/* Callback handling data */
SR_PRIV int demo_prepare_data(int fd, int revents, void *cb_data)
{
	struct sr_dev_inst *sdi;
	struct dev_context *devc;
	struct sr_datafeed_packet packet;
	struct analog_gen *ag;
	GHashTableIter iter;
	void *value;
    int i;

	(void)fd;
	(void)revents;

	sdi = cb_data;
	devc = sdi->priv;

    static int once = 0;
    if (!once) {
		pthread_setname_np(pthread_self(), "session_rx");
        cpu_set_t mask;
        CPU_ZERO(&mask);
        CPU_SET(3,&mask);
        printf("thread %lu bind to core 3\n", pthread_self());
        if(-1 == pthread_setaffinity_np(pthread_self() ,sizeof(mask),&mask))
        {
            fprintf(stderr, "pthread_setaffinity_np erro\n");
            return -1;
        }
		int policy = SCHED_OTHER;
		policy = SCHED_FIFO;
		struct sched_param sp = {0};
		sp.sched_priority = 50;
		pthread_setschedparam(pthread_self(), policy, &sp);

        once = 1;
    }

	/* Just in case. */
	if (devc->cur_samplerate <= 0
			|| (devc->num_logic_channels <= 0
			&& devc->num_analog_channels <= 0)) {
		sr_dev_acquisition_stop(sdi);
		return G_SOURCE_CONTINUE;
	}

    //printf("time: %lu\n", g_get_monotonic_time());

    for (i = 0; i < devc->num_analog_channels; i++) {
    	send_analog_packet(devc->ag_tbl[i], sdi);
    }


	if (devc->limit_frames && devc->sent_frame_samples >= SAMPLES_PER_FRAME) {
		std_session_send_df_frame_end(sdi);
		devc->sent_frame_samples = 0;
		devc->limit_frames--;
		if (!devc->limit_frames) {
			sr_dbg("Requested number of frames reached.");
			sr_dev_acquisition_stop(sdi);
		}
	}

	if (devc->limit_samples > 0 && devc->sent_samples >= devc->limit_samples) {

		/* If we're averaging everything - now is the time to send data */
		if (devc->avg && devc->avg_samples == 0) {
			g_hash_table_iter_init(&iter, devc->ch_ag);
			while (g_hash_table_iter_next(&iter, NULL, &value)) {
				ag = value;
				packet.type = SR_DF_ANALOG;
				packet.payload = &ag->packet;
				ag->packet.data = &ag->avg_val;
				ag->packet.num_samples = 1;
				sr_session_send(sdi, &packet);
			}
		}
		sr_dbg("Requested number of samples reached.");
		sr_dev_acquisition_stop(sdi);
	} else if (devc->limit_frames) {
		if (devc->sent_frame_samples == 0)
			std_session_send_df_frame_begin(sdi);
	}

	return G_SOURCE_CONTINUE;
}
